﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows.Forms;

namespace ImmlPad
{
    public class SingleInstanceMain
    {
        [STAThread]
        public static void Main(string[] args)
        {
            _VerifyNetFramework(); //verify .NET 3.5 SP1 is installed correctly

            SingleInstanceManager manager = new SingleInstanceManager();
            manager.Run(args);
        }

        private static void _VerifyNetFramework()
        {
            //TODO: The registry trick here may not work on mono

            Microsoft.Win32.RegistryKey netFrameworkKey = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey spKey = netFrameworkKey.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP\v3.5");
            object spValue = spKey.GetValue("SP");

            if (Convert.ToInt32(spValue) < 1)
            {
                //sp1 is missing
                MessageBox.Show(".NET Framework 3.5 SP1 is required but it appears the service pack is not installed correctly. Please install the service pack (or restart your computer if you have recently installed it) before attempting to run this application.", ".NET Framework 3.5 SP1 missing");
                Environment.Exit(0);
            }
        }
    }

    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        private App _App;

        public SingleInstanceManager()
        {
            this.IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            _App = new App();
            _App.Run();
            return false;    
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {            
            base.OnStartupNextInstance(eventArgs);

            //TODO: only prevent opening next instance if there are 0 args, 
            //ie: if someone ran the ImmlPad exe again

            var args = new List<string>();

            if (eventArgs.CommandLine.Count > 0)
            {
                eventArgs.BringToForeground = true;

                foreach (string arg in eventArgs.CommandLine)
                {
                    args.Add(arg);
                }
            }

            _App.Signal(args);
        }
    }
}
